package com.aiti.lulian.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author ZhouS
 * @CreateDate 2022-09-16
 * @Description:
 */
public class MapUtils {


    /**
     *根据经纬度获取省市区
     */
    public static String getAddressStr(String log, String lat){
        //lat 小  log  大
        String key = "503b50ff7c33d5635dbe1e1563e20a7f";
        String parameters="?key="+key;
        parameters+="&location="+log+","+lat;//经纬度坐标
        parameters+="&extensions=true";//返回结果控制，extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
        parameters+="&radius=1";//搜索半径，radius取值范围在0~3000，默认是1000。单位：米
        parameters+="&batch=false";
        parameters+="&roadlevel=0";

        String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
        StringBuilder res = new StringBuilder();
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line).append("\n");
            }
            in.close();
            //解析结果
            JSONObject jsonObject = JSONObject.parseObject(res.toString());
            System.out.println("jsonObject = " + jsonObject);
            JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
            res = new StringBuilder(jsonObject1.getString("formatted_address"));
            JSONObject jsonObject2 = jsonObject1.getJSONObject("addressComponent");
            StringBuilder privince= new StringBuilder(jsonObject2.getString("province"));
            System.out.println("privince:"+privince);
            StringBuilder city= new StringBuilder(jsonObject2.getString("city"));
            System.out.println("city:"+city);
            StringBuilder district= new StringBuilder(jsonObject2.getString("district"));
            System.out.println("district:"+district);


        } catch (Exception e) {
            System.out.println("获取地址信息异常");
            e.printStackTrace();
            return null;
        }
        System.out.println("通过API获取到具体位置:"+res);

        return res.toString();
    }



    /**
     *根据经纬度获取省市区
     */
    public static Map getAddress(String log, String lat){
        Map map=new HashMap();
        //lat 小  log  大
        String key = "503b50ff7c33d5635dbe1e1563e20a7f";
        String parameters="?key="+key;
        parameters+="&location="+log+","+lat;//经纬度坐标
        parameters+="&extensions=true";//返回结果控制，extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
        parameters+="&radius=1";//搜索半径，radius取值范围在0~3000，默认是1000。单位：米
        parameters+="&batch=false";
        parameters+="&roadlevel=0";

        String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
        StringBuilder res = new StringBuilder();
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line).append("\n");
            }
            in.close();
            //解析结果
            JSONObject jsonObject = JSONObject.parseObject(res.toString());
            System.out.println("jsonObject = " + jsonObject);
            JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
            res = new StringBuilder(jsonObject1.getString("formatted_address"));

            System.out.println("通过API获取到具体位置:"+res);
            JSONObject jsonObject2 = jsonObject1.getJSONObject("addressComponent");
            StringBuilder privince= new StringBuilder(jsonObject2.getString("province"));
            System.out.println("privince:"+privince);
            StringBuilder city= new StringBuilder(jsonObject2.getString("city"));
            System.out.println("city:"+city);
            StringBuilder district= new StringBuilder(jsonObject2.getString("district"));
            System.out.println("district:"+district);
             map.put("privince",privince.toString());
            map.put("city",city.toString());
            map.put("district",district.toString());
            map.put("address",res.toString());
        } catch (Exception e) {
            System.out.println("获取地址信息异常");
            e.printStackTrace();
            return null;
        }


        return map;
    }

  public static void main(String[] args) {
    /*getLonAndLat("山东省济南市天桥区虎泉信息科技中心");*/


      System.out.println(generateCode());
    }

    public static String generateCode() {
        Random random = new Random();
        int code = random.nextInt(9000) + 1000; // 生成4位数的验证码
        return String.valueOf(code);
    }

   public static Map getLonAndLat(String address) {
       String key = "503b50ff7c33d5635dbe1e1563e20a7f";
       // 返回输入地址address的经纬度信息, 格式是 经度,纬度
       String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address;
       // 高德接口返回的是JSON格式的字符串
       String queryResult = getResponse(queryUrl);
       Map<String, String> map = new HashMap<String, String>();
       JSONObject obj = JSONObject.parseObject(queryResult);
       if (obj.get("status").toString().equals("1")) {
           JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1, obj.get("geocodes").toString().length() - 1));
           String location = jobJSON.get("location").toString();
           System.out.println("经纬度：" + location);
           String[] lonAndLat = location.split(",");
           if (lonAndLat != null && lonAndLat.length == 2) {
               map.put("lng", lonAndLat[0]);
               map.put("lat", lonAndLat[1]);
           }
           System.out.println(map);
           return map;
       } else {
           throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
       }
   }

    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
